﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntityFrameworkETL.SaveBatchedChanges;

namespace EntityFrameworkETL.Interceptors
{
    public class CommandCacheInterceptor : IDbCommandInterceptor
    {
        #region UnusedMembers
        public void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            throw new NotImplementedException();
        }

        public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            throw new NotImplementedException();
        }

        public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
        }

        public void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            throw new NotImplementedException();
        }

        public void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            throw new NotImplementedException();
        }

        #endregion

        public CommandCacheInterceptor()
        {
            CommandCaches = new List<CommandCache>();
            FakeReaderGenerator = new FakeReaderGenerator();
        }

        public CommandCacheInterceptor(IFakeReaderGenerator fakeReaderGenerator = null)
            : this()
        {
            if (fakeReaderGenerator != null)
                FakeReaderGenerator = fakeReaderGenerator;
        }

        public List<CommandCache> CommandCaches { get; set; }
        public IFakeReaderGenerator FakeReaderGenerator { get; set; }

        public void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            interceptionContext.SuppressExecution();
            var commandCache = new CommandCache(command);
            interceptionContext.Result = FakeReaderGenerator.GetReader(commandCache);
            commandCache.FakeId = FakeReaderGenerator.CurrentPrimaryKey();
            CommandCaches.Add(commandCache);
        }
    }
}
